package cfca.seal.web.action.assist;

import cfca.sadk.x509.certificate.X509Cert;
import cfca.seal.bean.AdminUser;
import cfca.seal.bean.OperationLog;
import cfca.seal.exception.CodeException;
import cfca.seal.mananger.OperationLogManager;
import cfca.seal.system.Env;
import cfca.seal.util.PwdEncryptUtil;
import cfca.seal.util.StringUtil;
import cfca.seal.util.TimeUtil;
import cfca.seal.web.service.ManagerService;
import cfca.seal.web.service.OperationLogService;
import cfca.seal.web.system.SessionManager;
import java.security.cert.X509Certificate;
import java.util.Date;
import java.util.Enumeration;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
public class LoginAction
{
  private static Logger sysLogger = LoggerFactory.getLogger("web_sys");

  private String loginInputPage = "sys/login.html";
  private String format = "yyyy-MM-dd HH:mm";

  @Resource
  private ManagerService managerService;

  @Resource
  private OperationLogService operationLogService;

  @RequestMapping(value={"/login"}, method={org.springframework.web.bind.annotation.RequestMethod.GET})
  public String input(ModelMap map, HttpServletRequest request)
    throws Exception
  {
    request.getSession().setAttribute("root", request.getContextPath());
    request.setAttribute("nowTime", TimeUtil.getCurrentTime(this.format));
    request.setAttribute("version", Env.version);

    AdminUser manager = SessionManager.getManager(request);
    if (manager != null) {
      return "redirect:/frame.do";
    }

    if (request.getRequestURL().toString().contains("https://"))
    {
      X509Certificate cert = null;
      X509Cert cfcaCert = null;
      String certDn = null;
      String certSn = null;
      X509Certificate[] certs = (X509Certificate[])request.getAttribute("javax.servlet.request.X509Certificate");

      if ((null != certs) && (certs.length > 0)) {
        cert = certs[0];
        cfcaCert = new X509Cert(cert.getEncoded());
        certDn = cfcaCert.getSubject();
        certSn = cfcaCert.getStringSerialNumber();
        sysLogger.info("管理员证书方式登录系统:");
        sysLogger.info("DN=" + certDn);
        sysLogger.info("SN=" + certSn);

        OperationLog operationLog = OperationLogManager.getInstance("", "用户登录", "登录", "", "管理员证书方式登录系统,DN:" + certDn + ",SN:" + certSn, null);

        operationLog.setResult(20);

        AdminUser adminUser = this.managerService.getAdminUserByDnAndSn(certDn, certSn);
        if (null == adminUser) {
          sysLogger.error("管理员证书方式登录系统失败：未找到使用该证书的管理员信息");
          operationLog.setResult(10);
          this.operationLogService.addOperationLog(operationLog);
          throw new CodeException("C1000", "未找到使用该证书的管理员信息");
        }

        adminUser.setLastLoginDate(new Date());
        adminUser.setLoginErrorTimes(0);
        SessionManager.saveManager(request, adminUser);
        SessionManager.saveUrlType(request, "https");
        sysLogger.info("管理员" + adminUser.getName() + "证书登录系统成功");
        this.managerService.loginUpdate(adminUser);

        operationLog.setOperator(adminUser.getId());
        this.operationLogService.addOperationLog(operationLog);
        return "redirect:/frame.do";
      }
    }

    return this.loginInputPage;
  }

  @RequestMapping(value={"/login"}, method={org.springframework.web.bind.annotation.RequestMethod.POST})
  public String specilLogin(ModelMap map, HttpServletRequest request)
    throws CodeException
  {
    OperationLog operationLog = OperationLogManager.getInstance(request.getParameter("name"), "用户登录", "登录", "", "用户密码方式登录系统", null);
    operationLog.setResult(10);
    try
    {
      request.getSession().setAttribute("root", request.getContextPath());
      request.setAttribute("version", Env.version);
      request.setAttribute("nowTime", TimeUtil.getCurrentTime(this.format));
      String name = request.getParameter("name");
      String password = request.getParameter("password");
      String str1;
      if (StringUtil.isEmpty(name)) {
        map.put("error", "登录出错，用户名为空");
        sysLogger.error("登录出错，用户名为空");
        return this.loginInputPage;
      }

      if (StringUtil.isEmpty(password)) {
        map.put("error", "登录出错,密码为空");
        sysLogger.error("登录出错，密码为空,登录用户名：" + name);
        return this.loginInputPage;
      }

      AdminUser aManager = this.managerService.getManagerByName(name);
      String str2;
      if (aManager == null) {
        map.put("error", "登录出错,用户不存在");
        map.put("name", name);
        sysLogger.error("登录出错，用户不存在,登录用户名：" + name);
        return this.loginInputPage;
      }

      operationLog.setOperator(aManager.getId());
      operationLog.setOrganizationId(aManager.getOrganizationId());
      if (password.equals(PwdEncryptUtil.decrypto(aManager.getPassword()))) {
        aManager.setLastLoginDate(new Date());
        aManager.setLoginErrorTimes(0);
        SessionManager.saveManager(request, aManager);
        SessionManager.saveUrlType(request, "http");
        sysLogger.info("管理员" + aManager.getName() + "登录成功");
        this.managerService.loginUpdate(aManager);
        operationLog.setResult(20);
        return "redirect:/frame.do";
      }
      aManager.setLoginErrorTimes(aManager.getLoginErrorTimes() + 1);
      map.put("error", "密码错误!");
      map.put("name", name);
      sysLogger.error("登录失败，密码错误,错误次数：" + aManager.getLoginErrorTimes());
      this.managerService.loginUpdate(aManager);
      return this.loginInputPage;
    }
    catch (Exception e)
    {
      sysLogger.error("登录处理出现系统错误", e);
      throw new CodeException("C0001", e);
    } finally {
      this.operationLogService.addOperationLog(operationLog);
    }
  }

  @RequestMapping(value={"/frame"}, method={org.springframework.web.bind.annotation.RequestMethod.GET})
  public String frame(ModelMap map, HttpServletRequest request)
  {
    request.getSession().setAttribute("root", request.getContextPath());
    return "sys/frame/frame.html";
  }

  @RequestMapping(value={"/logout"}, method={org.springframework.web.bind.annotation.RequestMethod.GET})
  public String logout(HttpServletRequest request, HttpServletResponse response)
  {
    String userName = SessionManager.getName(request);
    if (StringUtil.isNotEmpty(userName))
      sysLogger.info("用户" + userName + "退出系统");
    else {
      sysLogger.info("用户未登录系统");
    }

    Enumeration enumeration = request.getSession().getAttributeNames();
    while (enumeration.hasMoreElements()) {
      String key = ((String)enumeration.nextElement()).toString();
      request.getSession().removeAttribute(key);
    }

    request.getSession().invalidate();
    request.setAttribute("root", request.getContextPath());
    sysLogger.info("清除会话成功");
    return "sys/logout.html";
  }
}